/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.audio
{
	import flash.events.Event;
	import com.qb9.flashlib.utils.ArrayUtil;
	
	/** Base class for all collections of Playables */
	public class PlayableCollection extends Playable
	{
		protected var tracks:Array;
		protected var activeIndex:uint;
		
		// ABSTRACT
		
		public function PlayableCollection(tracks:Array, id:String)
		{
			super(id);
			this.tracks = tracks;
			this.activeIndex = 0;
			
			for each(var track:IPlayable in tracks)
				track.addEventListener(Event.SOUND_COMPLETE, _onPlayComplete);
		}
		
		/**
		 * The asset currently being played
		 */
		public function get active() : IPlayable
		{
			return at(activeIndex);
		}
		
		/**
		 * Retrieves an asset a certain index
		 */
		public function at(index:uint) : IPlayable
		{
			return tracks[index];
		}
		
		/**
		 * The elapsed playback of the active asset 
		 */
		public override function get position() : Number
		{
			return active.position;
		}
		
		/** @inheritDoc */
		public override function set position(pos:Number) : void
		{
			active.position = pos;
		}
		
		/** @inheritDoc */
		public override function get volume() : Number
		{
			return active.volume;
		}

		/** @inheritDoc */
		public override function set volume(vol:Number) : void
		{
			super.volume = vol;
			active.volume = vol;		
		}
		
		/** @inheritDoc */
		public override function stop() : void
		{
			super.stop();
			active.stop();
		}
		
		/** @inheritDoc */
		public override function pause() : void
		{
			super.pause();
			active.pause();
		}
		
		/** @inheritDoc */
		public override function resume() : void
		{
			super.resume();
			active.resume();
		}
		
		/** @inheritDoc */
		public override function dispose() : void
		{
			stop();
			for each(var track:IPlayable in tracks)
			{
				track.dispose();
				track.removeEventListener(Event.SOUND_COMPLETE, _onPlayComplete);
			}
			tracks.length = 0;
		}
		
		/** Sort the tracks in random order */
		public function shuffle() : void
		{
			this.tracks = ArrayUtil.shuffle(this.tracks);
		}
	}
}
